package com.xzg.erp.system.web;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xzg.erp.common.BusinessException;
import com.xzg.erp.common.Constants;
import com.xzg.erp.system.entity.Attachment;
import com.xzg.erp.system.service.IAttachmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 附件表 前端控制器
 * </p>
 *
 * @author qwc
 * @since 2025-02-13
 */
@RestController
@RequestMapping("/attachment")
public class AttachmentController {

    @Autowired
    private IAttachmentService attachmentService;

    @GetMapping("/getByTable/{tableName}/{id}")
    public ResponseEntity getByTable(@PathVariable String tableName, @PathVariable String id) {
        List<Attachment> list = attachmentService.list(Wrappers.<Attachment>lambdaQuery()
                .eq(Attachment::getRelatedTable, tableName)
                .eq(Attachment::getRelatedTablePrimaryKey, id)
                .eq(Attachment::getDeleted, Constants.UN_DELETED));
        return ResponseEntity.ok(list);
    }

    @PostMapping("/upload")
    public ResponseEntity upload(@RequestParam("file") MultipartFile file, @RequestParam("id") int id, @RequestParam("tableName") String tableName) {
        attachmentService.saveFile(file, id, tableName);
        return ResponseEntity.ok(Constants.SUCCESS);
    }

    @PostMapping("/delete/{id}")
    public ResponseEntity delete(@PathVariable Integer id) {
        Attachment attachment = attachmentService.getById(id);
        attachment.setUpdatedAt(LocalDateTime.now());
        attachment.setUpdatedBy(StpUtil.getLoginIdAsInt());
        attachment.setDeleted(attachment.getId());
        attachmentService.updateById(attachment);
        return ResponseEntity.ok(Constants.SUCCESS);
    }

}
